package com.petdog.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Redis配置类
 * 用于配置Redis相关组件，在Redis服务器不可用时提供降级方案
 */
@Configuration
public class RedisConfig {
    
    /**
     * 创建一个模拟的RedisTemplate Bean
     * 当实际Redis连接不可用时，提供一个不依赖实际Redis的实现
     */
    @Bean
    @ConditionalOnMissingBean(RedisConnectionFactory.class)
    public RedisTemplate<String, String> redisTemplate() {
        // 创建一个简单的RedisTemplate实现，使用ConcurrentHashMap模拟Redis存储
        RedisTemplate<String, String> template = new RedisTemplate<>();
        // 设置序列化器
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        // 简单实现，不依赖实际连接
        return template;
    }
}
